package com.zhongwang.business.module.system.user;

import com.zhongwang.business.base.BaseController;
import com.zhongwang.business.common.JsonResult;
import com.zhongwang.business.common.ValidResult;
import com.zhongwang.business.gen.entity.Org;
import com.zhongwang.business.gen.entity.Role;
import com.zhongwang.business.gen.entity.User;
import com.zhongwang.business.module.system.dept.Dept;
import com.zhongwang.business.module.system.dept.DeptService;
import com.zhongwang.business.module.system.log.LogService;
import com.zhongwang.business.module.system.org.OrgService;
import com.zhongwang.business.module.system.role.RoleService;
import com.zhongwang.business.util.FileUtils;
import com.zhongwang.business.util.ShiroUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

import static com.zhongwang.business.constant.Constant.STATUS_NORMAL;


/**
 *  用户 控制层
 * @author China.sgl
 * @date 2019/9/16 09:11
 */
@Controller
@RequestMapping("/sys/user")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private LogService logService;
    @Autowired
    private UserDao userDao;
    @Autowired
    private OrgService orgService;
    @Autowired
    private DeptService deptService;

    @Value("${user.upload.path}")
    private String uploadPath;

    /**
     * 系统帐户页面
     *
     * @return 页面 URL
     */
    @GetMapping
    @RequiresPermissions({"system:user:view"})
    public String page() {
        return "system/user/page";
    }

    /**
     * 系统帐户数据
     *
     * @param user 查询条件封装
     * @return 系统帐户 Json 数据
     */
    @ResponseBody
    @PostMapping("/list")
    public JsonResult userList(User user) {
        startPage();
        List<User> list = userService.findAll(user);
        return jsonResult(list);
    }

    /**
     * 修改帐户
     *
     * @param user 帐户信息
     * @return json数数
     */
    @ResponseBody
    @PostMapping("/update")
    public JsonResult update(User user) {
        logService.saveLog((user.getStatus() == STATUS_NORMAL ? "解锁用户" : "锁定用户"), user.getName());
        return jsonResult(userService.updateUser(user));
    }

    /**
     * 重置帐户密码
     *
     * @param id 帐户 id
     * @return json数据
     */
    @ResponseBody
    @PostMapping("/reset")
    public JsonResult resetPassword(Integer id) {
        return jsonResult(userService.resetPassword2(id));
    }



    /**
     * 检查帐号是否存在
     *
     * @param account 帐号
     * @return json 数据
     */
    @ResponseBody
    @PostMapping("/checkUnique")
    public ValidResult checkUnique(String account) {
        User user = userService.findByAccount(account);
        return ValidResult.result(user);
    }

    /**
     * 创建帐户
     *
     * @param user    帐户信息
     * @param roleIds 选中角色 id 数组
     * @return json 数据
     */
    @ResponseBody
    @PostMapping("/save")
    public JsonResult save(User user, Integer[] roleIds) {
        logService.saveLog("创建用户", user.getName());
        return jsonResult(userService.saveUser(user, roleIds));
    }



    /**
     * 修改用户与角色
     *
     * @param user    用户信息
     * @param roleIds 选中角色 id 数组
     * @param orgId 选中部门 id
     * @return json 数据
     */
    @ResponseBody
    @PostMapping("/edit")
    public JsonResult update(User user, Integer[] roleIds, Integer orgId, Integer deptId) {
        return isNotNull(userService.updateUser(user, roleIds, orgId, deptId));
    }

    /**
     * 修改头像
     */
    @ResponseBody
    @PostMapping("/edit/img")
    public JsonResult updateImage(String imageData) {
        String imgName = UUID.randomUUID().toString() + ".png";
        User user = ShiroUtils.getUser();
        try {
            FileUtils.decodeBase64DataURLToImage(imageData, uploadPath, imgName);
            FileUtils.remove(uploadPath+user.getImg());
            user = userService.updateImage("/files/" + imgName,imageData);
        } catch (IOException e) {
            return JsonResult.fail("修改头像失败！");
        }
        return JsonResult.success("修改头像成功！", user.getImg());
    }

    /**
     * 查询所有角色，标识帐户拥有角色
     *
     * @param id 帐户 id
     * @return json 数据
     */
    @GetMapping("/roles/{id}")
    @ResponseBody
    public List<Role> roles(@PathVariable Integer id) {
        return roleService.findRolesCheckedByUserId(id);
    }

    /**
     * 查询用户
     *
     * @param id 用户id
     * @return 用户
     */
    @ResponseBody
    @PostMapping("/id")
    public User id(Integer id) {
        return userService.findUserById(id);
    }

    /**
     * 员工编号存在校验
     * 页面级校验
     *
     * @param userCode
     * @return
     */
    @PostMapping("/accountExist")
    @ResponseBody
    public Boolean accountExist(String userCode) {

        User user = userDao.findTempUserInfo(userCode);
        return user == null ? false : true;
    }

    /**
     * 查询项目用户名称
     *
     * @param account 账号
     * @return 用户
     */
    @ResponseBody
    @GetMapping("/findTempUser")
    public JsonResult findTempUserByAccount(String account) {

        JsonResult jsonResult = new JsonResult();
        jsonResult.setType(JsonResult.ResultType.SUCCESS);

        User user = userDao.findTempUserInfo(account);
        jsonResult.setData(user == null ? "" : user.getName());
        return jsonResult;
    }

    /**
     * 获取头像
     *
     * @return 头像
     */
    @ResponseBody
    @PostMapping("/getImg")
    public byte[] getImg(){
        User user = userDao.findUserById(ShiroUtils.getUserId());
        return user.getImgBlob();
    }
    /**
     * 查询所有部门
     *
     * @return json数据
     */
    @GetMapping("/orgs")
    @ResponseBody
    public List<Org> orgs() {
        return orgService.findOrgByCondition(new Org());
    }

    /**
     * 查询所有部门，标识用户拥有部门
     *
     * @param id 用户 id
     * @return json 数据
     */
    @GetMapping("/depts/{id}")
    @ResponseBody
    public List<Dept> depts(@PathVariable Integer id) {
        return deptService.findDeptCheckedByUserId(id);
    }

    /**
     * 查询所有部门，标识用户拥有部门
     *
     * @param id 用户 id
     * @return json 数据
     */
    @GetMapping("/orgs/{id}")
    @ResponseBody
    public List<Org> orgs(@PathVariable Integer id) {
        return orgService.findOrgCheckedByUserId(id);
    }

}
